<?php
/*
 * @Author: wangzhixiang wangzhixiang@adxdata.com
 * @Date: 2023-04-23 16:00:25
 * @LastEditors: wangzhixiang wangzhixiang@adxdata.com
 * @LastEditTime: 2023-04-25 17:29:32
 * @FilePath: /once/application/api/controller/Firebase.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

namespace app\api\controller;

use app\common\controller\Api;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use JWage\APNS\Certificate;
use JWage\APNS\Client;
use JWage\APNS\Sender;
use JWage\APNS\SocketClient;

/**
 * Firebase
 *
 */
class Firebase extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // Firebase 项目ID
    protected $projects = 'emojo-riding';

    // 鉴权json
    protected $json_path = APP_PATH . 'emojo-riding-firebase-adminsdk-wst9a-fcd8dbed01.json';

    // protected $json_path = APP_PATH . 'neon-shelter-382006-firebase-adminsdk-hevyo-b3e0422a6a.json';

    //证书地址
    protected $anps_path = APP_PATH . 'apns.pem';

    /**
     * @description: 推送接口
     * @return {*}
     */
    public function send()
    {
        $request = $this->request;
        $token = $request->post('token', '');
        $title = $request->post('title', 'FCM Message');
        $body = $request->post('body', 'This is an FCM notification message!');
        if (empty($token)) {
            $this->error('Missing token!');
        }
        $factory = (new Factory)->withServiceAccount($this->json_path);
        $messaging = $factory->createMessaging();
        $message = CloudMessage::withTarget('token', $token)
            ->withNotification(Notification::create($title, $body))
            ->withData(['key' => 'value']);
        $result = $messaging->send($message);
        if (!$result) {
            //异常处理
            $this->error('error', $result);
        }

        $this->success('successfully', $result);
    }

    /**
     * @description: ios推送接口
     * @return {*}
     */
    public function push()
    {
        $request = $this->request;
        $token = $request->post('token', '');
        if (empty($token)) {
            $this->error('Missing token!');
        }
        $certificate = new Certificate(file_get_contents($this->anps_path));
        $socketClient = new SocketClient($certificate, 'gateway.push.apple.com', 2195);
        $client = new Client($socketClient);
        $sender = new Sender($client);
        $body = "This is an APNs notification message!";
        $title = "APNs Message";
        $result = $sender->send($token, $title, $body, 'http://baidu.com');
        
        $this->success('successfully', $result);
    }
}
